﻿
using System;
using System.Diagnostics;
using System.Windows.Forms;

using n_ET;
using n_GUIcoder;
using n_ISP;
using n_OS;
using n_TargetFile;
using n_MainSystemData;
using n_AVRdude;

namespace n_RemoPad
{
public static class RemoPad
{
	//========================================================================
	
	//串口下发事件(仿真时由硬件接收)
	public delegate void D_SendData( byte b );
	public static D_SendData deleSendData;
	
	//串行端口
	static System.IO.Ports.SerialPort port;
	static byte[] buffer;
	static byte[] write_buffer;
	static int PIndex;
	
	static System.Windows.Forms.Timer t;
	
	public const byte CMD_WAVE = 0;
	public const byte CMD_REMO = 1;
	public const byte CMD_USER = 2;
	
	//初始化调试器
	public static void DebugInit()
	{
		buffer = new byte[ 2000 ];
		PIndex = 0;
		
		write_buffer = new byte[100];
		
		t = new System.Windows.Forms.Timer();
		t.Interval = 1;
		t.Tick += new EventHandler( t_Tick );
		t.Enabled = false;
		
		n_ImagePanel.ImagePanel.dTick = t_Tick;
	}
	
	//----------------------------
	//示波器
	
	//开始调试
	public static bool OpenDebugOk()
	{
		string portname = AVRdude.PortName;
		if( portname == null ) {
			n_Debug.Warning.WarningMessage = "串口未找到, 请先点击下载程序按钮";
			return false;
		}
		if( port != null && port.IsOpen ) {
			return true;
		}
		return OpenOk( portname, 115200 );
	}
	
	//结束调试
	public static void StopDebug()
	{
		if( port != null && port.IsOpen ) {
			Debug_Open( 0 );
			System.Threading.Thread.Sleep( 50 );
			port.Close();
		}
		port = null;
	}
	
	//发送开关协议
	public static void Debug_Open( byte b )
	{
		if( port != null && port.IsOpen ) {
			SendCmdOk( CMD_WAVE, b, 0, 0, 0, 0, 0, 0 );
		}
	}
	
	//----------------------------
	//遥控器
	
	public static bool SendCmdOk( byte c, byte b, int v1, int v2, int v3, int v4, int v5, int v6 )
	{
		int Num = 29;
		
		write_buffer[0] = 0x5A;
		write_buffer[1] = 0x55;
		write_buffer[2] = 0;
		write_buffer[3] = c;
		write_buffer[4] = b;
		
		n_Data.Data.SetInt32(write_buffer, 5, v1 );
		n_Data.Data.SetInt32(write_buffer, 9, v2 );
		n_Data.Data.SetInt32(write_buffer, 13, v3 );
		n_Data.Data.SetInt32(write_buffer, 17, v4 );
		n_Data.Data.SetInt32(write_buffer, 21, v5 );
		n_Data.Data.SetInt32(write_buffer, 25, v6 );
		
		if( G.SimulateMode ) {
			if( deleSendData != null ) {
				for( int i = 0; i < Num; ++i ) {
					deleSendData( write_buffer[i] );
				}
			}
		}
		else {
			if( port == null ) {
				OpenDebugOk();
			}
			if( port != null ) {
				//port.Write( write_buffer, 0, Num );
				
				//115200波特率 发送必须要加延时, 否则下位机可能接收不过来!
				port.Write( write_buffer, 0, 10 ); System.Threading.Thread.Sleep( 10 );
				port.Write( write_buffer, 10, 10 ); System.Threading.Thread.Sleep( 10 );
				port.Write( write_buffer, 20, 9 ); System.Threading.Thread.Sleep( 10 );
			}
			else {
				return false;
			}
		}
		return true;
	}
	
	public static void CloseCmd()
	{
		if( port != null && port.IsOpen ) {
			port.Close();
		}
		port = null;
	}
	
	//----------------------------
	//打开端口
	static bool OpenOk( string COMNumber, int Baud )
	{
		port = new System.IO.Ports.SerialPort( COMNumber );
		port.BaudRate = Baud;
		port.DataBits = 8;
		port.Parity = System.IO.Ports.Parity.None;
		port.StopBits = System.IO.Ports.StopBits.One;
		port.ReadTimeout = 1;
		port.DtrEnable = false;
		port.RtsEnable = false;
		
		//port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler( DataReceived );
		try {
			port.Open();
		}
		catch(Exception e) {
			MessageBox.Show( "串口打开失败: " + e );
			port = null;
		}
		t.Enabled = true;
		return port != null;
	}
	
	static void t_Tick( object sender, EventArgs e )
	{
		if( port == null || !port.IsOpen ) {
			return;
		}
		int n = 0;
		try {
			if( port.BytesToRead != 0 ) {
				n = port.Read( buffer, 0, port.BytesToRead );
			}
		}
		catch( Exception ee) {
			n_Debug.Warning.BUG( "<RemoPad.t_Tick> 串口读取异常: " + ee.ToString() );
		}
		try {
			if( n != 0 ) {
				for( int i = 0; i < n; ++i ) {
					byte b = buffer[ i ];
					AddByte( b );
				}
			}
		}
		catch( Exception ee) {
			n_Debug.Warning.BUG( "<RemoPad.t_Tick> 数据解析异常: " + ee.ToString() );
		}
	}
	
	static int ErrorNumber;
	
	//添加一个字节到显示窗口
	static void AddByte( byte b )
	{
		buffer[ PIndex ] = b;
		++PIndex;
		if( PIndex == 1 ) {
			if( b != 0xAA ) {
				string mes = "出错次数:" + ErrorNumber + " - 示波器协议起始错误: " + b;
				n_Debug.Warning.BUG( mes );
				n_Debug.Warning.WarningMessage += mes + " ";
				ErrorNumber++;
				PIndex = 0;
			}
			return;
		}
		if( PIndex >= 8 ) {
			int sum = buffer[ 1 ] + buffer[ 2 ] + buffer[ 3 ] + buffer[ 4 ] + buffer[ 5 ] + buffer[ 6 ];
			if( sum % 256 != buffer[ 7 ] ) {
				PIndex = 0;
				string mes = "出错次数:" + ErrorNumber + " - 示波器数据校验异常 - Sum:" + sum + " 1-6:" +
							buffer[ 1 ] + "," + buffer[ 2 ] + "," + buffer[ 3 ] + "," + buffer[ 4 ] + "," + buffer[ 5 ] + "," + buffer[ 6 ] + ", 7:" + buffer[7];
				n_Debug.Warning.BUG( mes );
				n_Debug.Warning.WarningMessage += mes + " ";
				ErrorNumber++;
				return;
			}
			int Index = buffer[ 1 ];
			Index += buffer[ 2 ] * 256;
			long data = buffer[ 3 ];
			data += buffer[ 4 ] * 256u;
			data += buffer[ 5 ] * 256u * 256u;
			data += buffer[ 6 ] * 256u * 256u * 256u;
			if( ( data & 0x80000000 ) != 0 ) {
				data = -( ( data ^ 0xffffffff ) + 1 );
			}
			if( Index == 0xFFFF ) {
				G.RemoBox.SetRet( (int)data );
			}
			else {
				n_MyObject.MyObject[] mol = G.CGPanel.myModuleList.ModuleList;
				
				try {
				mol[Index].AddDebugData( (int)data );
				mol[Index].DebugOpen = true;
				}
				catch {
					string mes = "示波器数据解析执行异常: ID-" + Index + ", L:" + mol.Length + ", D:" + data;
					n_Debug.Warning.BUG( mes );
					n_Debug.Warning.WarningMessage += mes + " ";
				}
			}
			PIndex = 0;
			G.CGPanel.MyRefresh();
		}
	}
}
}




